package com.example.demo.web;

import com.example.demo.common.CommonResult;
import com.example.demo.event.guava.EventBusService;
import com.example.demo.event.guava.IntegralEventListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.*;

/**
 * Created by lyc on 2019/6/13.
 */
@RestController
public class DelayedResultAction {


    @Autowired
    private EventBusService eventBusService;

    private static ExecutorService executor = Executors.newFixedThreadPool(10);

    /**
     * 延时结果请求 基于发布订阅机制
     * 效果 就是 异步处理 同步返回响应结果
     * @return
     */
    @GetMapping("delayed")
    public DeferredResult get(){
        //处理业务1
        DeferredResult deferredResult = new DeferredResult();
        //监听器处理 业务2
        eventBusService.register(new IntegralEventListener());
        eventBusService.post(deferredResult);
        return deferredResult;
    }


    /**
     * 常规callable
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @GetMapping("delayedCall")
    public Object getString() throws ExecutionException, InterruptedException {
        Future future = executor.submit(new Callable() {
            //处理业务1
            @Override
            public CommonResult call() throws Exception {
                Thread.sleep(1000);
               return new CommonResult();
            }
        });
        //处理业务2
       return future.get();
    }
}
